<template>
	<view>
		<view class="box-bg" v-if="status=='编辑'">
			<uni-nav-bar shadow left-icon="left" title="编辑收货地址" @clickLeft="back" />
		</view>
		<view class="box-bg" v-if="status=='新增'">
			<uni-nav-bar shadow left-icon="left" title="新增收货地址" @clickLeft="back" />
		</view>
		<uni-card>
			<uni-forms ref="form" :model="Address" labelWidth="80px">
				<uni-forms-item label="收货地址" name="addressLine">
					<uni-easyinput type="input" v-model="user.userName" placeholder="请输入收件人姓名" />
					<uni-easyinput type="input" v-model="user.userPhone" placeholder="请输入联系方式" />
					<uni-easyinput type="textarea" v-model="Address.addressLine" placeholder="请输入收货地址" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		<button type="primary" class="fixed-bottom" @click="submit">提交</button>
	</view>
</template>

<script>
	import {
		addUserAddress,
		getAddressDetail,
		updateUserAddress
	} from "@/api/system/user.js"
	export default {
		data() {
			return {
				status: '',
				Address: {
					addressId: '',
					useId: '',
					addressLine: "",
				},
				user: {
					userId: "",
					userName: "",
					userPhone: "",
				}
			}
		},
		onLoad(options) {
			// 从 URL 参数中获取操作类型和地址 ID
			const {
				addressId,
				action
			} = options;

			// 判断操作类型
			if (action === 'edit') {
				// 如果是编辑操作，则根据地址 ID 获取地址信息并填充表单
				this.status = "编辑";
				this.Address.addressId = parseInt(addressId);
				this.getAddressById(); // 传递 addressId 参数
			} else {
				// 如果是添加操作，则初始化一个空白的表单
				this.status = "新增";
				this.initEmptyForm();
			}
			this.getUserInfo();
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			getAddressById() {
				getAddressDetail(this.Address.addressId).then(res => {
					console.log(res);
					this.Address.addressLine = res.data.addressLine;
				})
			},
			initEmptyForm() {
				// 初始化一个空白的表单
				// ...
				this.status = "新增";
			},
			submit() {
				if (this.status === "编辑") {
					this.updateAddress();
				} else if (this.status === "新增") {
					this.addAddress();
				}

			},
			updateAddress() {
				updateUserAddress(this.Address).then(res => {
					uni.showToast({
						title: '编辑成功',
						icon: 'success',
						duration: 2000
					})
					this.back();
				})
			},
			addAddress() {
				addUserAddress(this.Address).then(res=>{
					uni.showToast({
						title: '新增成功',
						icon: 'success',
						duration: 2000
					})
					this.back();
				})
			},
			getUserInfo() {
				this.$store.dispatch('GetInfo').then(res => {
					if (res.appUser) {
						this.user.userName = res.appUser.userName;
						this.user.userId = res.appUser.userId;
						this.Address.userId = res.appUser.userId;
						this.user.userPhone = res.appUser.userPhone;
					}
				})
			}
		}
	}
</script>

<style>
	.box-bg {
		background-color: #F5F5F5;
		padding: 5px 0;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ff5722;
		/* 设置按钮的背景颜色 */
	}
</style>